package com.young.common.expression.dns;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.young.common.expression.AviatorRegexMatcher;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description：
 * @author: yangyahui01
 * @date: 11/29/24 12:45 PM
 */
public final class CachedMatcher {
    private static final LoadingCache<String, AviatorRegexMatcher> CACHE;

    public CachedMatcher() {
    }

    public static boolean match(String pattern, String target) {
        AviatorRegexMatcher matcher = (AviatorRegexMatcher)CACHE.get(pattern);
        return matcher.match(target);
    }

    public static String find(Map<String, String> container, String target) {
        if (container == null) {
            return null;
        } else {
            Iterator var2 = container.entrySet().iterator();

            Map.Entry entry;
            boolean matched;
            do {
                if (!var2.hasNext()) {
                    return null;
                }

                entry = (Map.Entry)var2.next();
                String pattern = (String)entry.getKey();
                matched = match(pattern, target);
            } while(!matched);

            return (String)entry.getValue();
        }
    }

    public static void clear() {
        CACHE.cleanUp();
    }

    public static void main(String[] args) {
        String pattern = ".*.baidu.com";
        AviatorRegexMatcher matcher = new AviatorRegexMatcher(pattern);
        System.out.println(matcher.match("www.baidu.com"));
        System.out.println(matcher.match("baidu.com"));
        Map<String, String> domainMap = new LinkedHashMap();
        domainMap.put("w.*.ab.*.com", "10.32.16.112");
        System.out.println(domainMap.toString());
    }

    static {
        CACHE = Caffeine.newBuilder().expireAfterWrite(12L, TimeUnit.MINUTES).maximumSize(1024L).build(AviatorRegexMatcher::new);
    }
}
